package com.by.interceptor;

import com.by.token.TokenTemplate;
import com.by.token.ValidResult;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * date 2025/2/12 19:13
 * author bjj
 * decoration
 * version 1.0
 * since jdk11
 */
public class TokenInterceptor implements HandlerInterceptor {
    TokenTemplate tokenTemplate;

    public TokenInterceptor(TokenTemplate tokenTemplate) {
        this.tokenTemplate = tokenTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            fail(response,"token不能为空");
            return false;
        }
        ValidResult validResult = tokenTemplate.valid(token);
        if(validResult.getCode()!=3){
            fail(response,validResult.getMsg());
            return false;
        }
        Map user = validResult.getPayload();
        return true;
    }

    void fail(HttpServletResponse response,String msg){
        response.setContentType("application/json;charset=utf-8");
        try(PrintWriter printWriter=response.getWriter()){
            printWriter.write("{\"code\":401,\"msg\":"+msg+"\"}");
        }catch (IOException e){
            throw new RuntimeException(e);
        }

    }
}
